package com.sqfw.framework.task;

import com.alibaba.fastjson2.JSONObject;
import com.sqfw.common.exception.base.BaseException;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.project.knowledge.service.ElderlyAllowanceService;
import com.sqfw.project.utils.HttpClientUtils;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import com.sqfw.project.wp.service.TSMSSendLogService;
import com.sqfw.project.wpReport.domain.WpHoliday;
import com.sqfw.project.wpReport.mapper.WpHolidayMapper;
import com.sqfw.project.zj.domain.ZjRecord;
import com.sqfw.project.zj.service.IZjRecordService;
import com.sqfw.project.zj.service.ScheduledTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.sqfw.common.utils.StringUtils;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("ryTask")
@Slf4j
public class RyTask
{
    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    private static final Logger logger = LoggerFactory.getLogger(RyTask.class);

    @Value("${yuyindb.url}")
    private String url;

    @Value("${yuyindb.user}")
    private String user;

    @Value("${yuyindb.psd}")
    private String psd;

    @Value("${zj-record.record-file-path-prefix}")
    private String recordFilePathPrefix;

    @Value("${server.port}")
    private String port;

    @Value("${smgp.checkSmsUrl}")
    private String checkSmsUrl;


    @Autowired
    private IZjRecordService iZjRecordService;

    @Autowired
    private TSMSSendLogService tsmsSendLogService;

    @Autowired
    private WpInfoMapper wpInfoMapper;

    @Autowired
    private WpHolidayMapper wpHolidayMapper;

    public void syncRecordData() throws SQLException, ClassNotFoundException {

        if (!"8091".equals(port)) {
            return;
        }
        // 本地录音表中CREATE_TIME 最近时间
        ZjRecord lastRecord = iZjRecordService.selectLastRecord();
        String lastRecordDate = lastRecord == null ? "1970-1-1 00:00:00"
                : DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", lastRecord.getCreateTime());
        Class.forName("com.mysql.cj.jdbc.Driver");
        log.info("查询时间：{}", lastRecordDate);
        // 查询语音系统 db_record_event时间大于lastRecordDate的
        Connection conn = DriverManager.getConnection(url, user, psd);

        String schema = conn.getSchema();
//        String sql = "select * from " + schema + ".db_record_event where eventTime > '" + lastRecordDate + "'"+"and eventname = 'RECORD_STOP'";

        String sql = "select * from (select DISTINCT e.RECORDID, e.RECORDUUID, e.AGENTID, e.ani, e.dnis, e.recordDir, e.recordFilepath, e.recordSeconds, e.startrecordtime, e.eventTime, e.callDirection, n.SIPCALLID from "
                + schema + ".DB_RECORD_EVENT e join "
                + schema + ".DB_CONTACT_INFO n on e.RECORDUUID = n.RECORDUUID where e.AGENTID not in('3132', '3158') and e.eventname = 'RECORD_STOP' and e.eventTime >'"
                + lastRecordDate + "') t1 left join (select DISTINCT n2.SIPCALLID as SIPCALLID2, m.UUID, m.SATISFIEDID from "
                + schema + ".DB_CONTACT_INFO n2 join "
                + schema + ".MANYIDU m on n2.OTHERLEGCONTACTID = m.UUID) t2 on t1.SIPCALLID = t2.SIPCALLID2";

        PreparedStatement preparedStatement = conn.prepareStatement(sql);

        ResultSet resultSet = preparedStatement.executeQuery();
        logger.info("获取语音数据成功");
        List<ZjRecord> zjRecords = new ArrayList<>();
        while (resultSet.next()) {
            ZjRecord zjRecord = new ZjRecord();
            zjRecord.setRecordId(resultSet.getString("recordId")); // 录音ID
            zjRecord.setRecordUuid(resultSet.getString("recordUuid")); // 录音UUID
            zjRecord.setAgentId(resultSet.getString("agentId")); // 坐席工号
            if (StringUtils.isEmpty(zjRecord.getAgentId())){
                zjRecord.setAgentId(null);
            }
            zjRecord.setAni(resultSet.getString("ani")); // 主叫号码
            zjRecord.setDnis(resultSet.getString("dnis")); // 被叫号码
            zjRecord.setRecordDir(resultSet.getString("recordDir")); // 录音地址
            zjRecord.setRecordFilepath(resultSet.getString("recordFilepath")); // 录音文件地址
            zjRecord.setRecordSeconds(resultSet.getString("recordSeconds")); // 通话时长（秒转化为  x分x秒）
            //录音开始时间
            zjRecord.setRecordStartTime(DateUtils.parseDate(resultSet.getString("startrecordtime")));
            //录音结束时间
            zjRecord.setRecordEndTime(DateUtils.parseDate(resultSet.getString("eventTime")));
            //事件时间做为开始时间
            zjRecord.setCreateTime(DateUtils.parseDate(resultSet.getString("eventTime"))); // 录音创建时间
            // 满意度： 满意：1  一般：2  不满意：3
            String satisfied = resultSet.getString("SATISFIEDID");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(satisfied)) {
                if ("1".equals(satisfied)) {
                    zjRecord.setSatisfaction("满意");
                }else if ("2".equals(satisfied)) {
                    zjRecord.setSatisfaction("一般");
                }else {
                    zjRecord.setSatisfaction("不满意");
                }
            }
            String callType = resultSet.getString("callDirection");
            if ("1".equals(callType)) zjRecord.setCallType("呼入");
            if ("0".equals(callType)) zjRecord.setCallType("拨出"); // 呼叫类型
            zjRecord.setZjStatus("待质检");
            zjRecord.setZjType("待质检");
            // 匹配工单号
            String wpid = iZjRecordService.getWpidByRecordId(zjRecord.getRecordUuid());
            zjRecord.setWpid(wpid);
            if (StringUtils.isNotEmpty(wpid)){
                WpInfo wpInfo = wpInfoMapper.selectWpInfoByWpId(wpid);
                if (wpInfo!=null){
                    zjRecord.setDepartment(wpInfo.getDeptLevel2());
                    if(StringUtils.isNotEmpty(zjRecord.getSatisfaction())){
                        wpInfoMapper.updateWpInfo3(wpid);
                    }
                }

            }
            //录音编号
            zjRecord.setRecordNum(zjRecord.getRecordUuid());
            zjRecords.add(zjRecord);
        }
        // 插入理想的库
        if (zjRecords.size() > 0) {
            for (ZjRecord z : zjRecords) {
                iZjRecordService.insertZjRecord(z);
            }
        }
        logger.info("同步录音信息结束，共同步" + zjRecords.size() + "条录音数据");
        resultSet.close();
        preparedStatement.close();
        conn.close();
    }

    public void taskCbdw() throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> list = new ArrayList<>();
        WpInfo wp = new WpInfo();
        String dateStr = "2023-12-18 00:00:00";
        Date parse1 = simpleDateFormat.parse(dateStr);
        wp.setBegainTime(parse1);
       List<WpInfo> wpInfos = wpInfoMapper.selectWpInfoListByDeptAndStarttime(wp);

        for (WpInfo wpInfo : wpInfos) {
            WpInfo info = new WpInfo();
            info.setScid(wpInfo.getScid());
            Date date = this.checkOntime(wpInfo.getStarttime(), wpInfo.getTimelimite());
            String format = simpleDateFormat.format(date);
            info.setTimeBoundry(format);

           int i =  wpInfoMapper.updateWpInfoTimeBoundry(info);

           if (i==0){
               list.add(wpInfo.getScid());
           }

        }
        if (list.size()>0){
            log.info("未更新成功的id集合：{}",StringUtils.join(list, "/"));
        }
    }

    private Date checkOntime(Date date, Integer day) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        WpHoliday wpHoliday = new WpHoliday();
        wpHoliday.setYearid(2023L);
        List<WpHoliday> wpHolidays = wpHolidayMapper.selectWpHolidayList(wpHoliday);

        WpHoliday wpHoliday1 = new WpHoliday();
        wpHoliday.setYearid(2024L);

        List<WpHoliday> wpHolidays1 = wpHolidayMapper.selectWpHolidayList(wpHoliday1);
        wpHolidays.addAll(wpHolidays1);
        List<String> dates = wpHolidays.stream()
                .map(WpHoliday::getDtime)
                .map(simpleDateFormat::format)
                .collect(Collectors.toList());
        String lasetDate = "";
        for (int i = 1; i <= day; i++) {
            lasetDate = addDay(date, i);
            if (dates.contains(lasetDate)) {
                day++;
            }
        }
        Date parseCon = null;
        try {
            Date parse = simpleDateFormat.parse(lasetDate);
            String format = DateFormatUtils.format(parse, "yyyy-MM-dd 23:59:59");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            parseCon = dateFormat.parse(format);
        } catch (ParseException e) {
            throw new BaseException("日期转换错误！");
        }
        return parseCon;

    }

    /**
     * @param date 日期
     * @return 加算后的日期
     * @Description 参数的日期加指定的日
     */
    private static String addDay(Date date, int day) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);

        return simpleDateFormat.format(calendar.getTime());
    }


    public void checkAndSendSms() {
        if (!"8091".equals(port)) {
            return;
        }
        String jsonString = HttpClientUtils.get(checkSmsUrl, null);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        if (jsonObject == null) {
            throw new BaseException("检验分机接口连接超时！");
        }
        Integer count = jsonObject.getInteger("count");
        if (count == 0) {
            //代表分机全部掉线，需要发送短信
            tsmsSendLogService.sendSms();
        }

    }

    @Autowired
    private ElderlyAllowanceService elderlyAllowanceService;

    public void test(String cetf) {
        elderlyAllowanceService.queryElderlyAllowance(cetf);
    }


}
